package com.xnew.file.controller;

import com.alibaba.fastjson.JSONObject;
import com.xnew.aes.SecurityParameter;
import com.xnew.bean.common.FileInfo;
import com.xnew.bean.common.SysUserInfo;
import com.xnew.constant.Constant;
import com.xnew.file.service.FileCommonService;
import com.xnew.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.List;


/**
 * @Author yangchengdong
 * @Date 2020/12/23
 */
@RestController
@RequestMapping("/file")
public class FileCommonController {

    @Autowired
    private FileCommonService fileCommonService;
    @Autowired
    private FileFtpUtil fileFtpUtil;



    private final Logger logger = LoggerFactory.getLogger(this.getClass());

//    /**
//     * 上传附件公共方法
//     * @param request
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping("/fileUploadCommon")
//    @SecurityParameter(outEncode = false)
//    public String fileUploadCommon(@RequestParam("file") MultipartFile[] loadFile, HttpServletRequest request) {
//        DataOutput out = DataOutput.success();
//        String fileName = loadFile[0].getOriginalFilename();
//        if (StringUtils.isBlank(fileName)) {
//            return ResponseUtil.responseMsg("-80004", "操作失败,上传文件名为空");
//        }
//        try {
//            // 请求中获取AuUser对象
//            SysUserInfo userInfo = (SysUserInfo) request.getSession().getAttribute(Constant.LOGIN_USER);
//            if (userInfo == null) {
//                return ResponseUtil.responseMsg("-20006", "用户未登录");
//            }
//            String message = new FileUtil().uploadFile(loadFile[0], userInfo.getUserInfoNo(), fileName);
//            JSONObject jsonObj = JSONObject.parseObject(message);
//            String fileId = jsonObj.getString("fileID");// 获取接口返回的文件id
//            String redisKey = RedisUtil.buildKey(":", new String[]{Constant.FILE_PREFIX, fileId});
//            RedisUtil.set(redisKey, fileName);
//            RedisUtil.expire(redisKey, 24*60*60);
//            return ResponseUtil.responseMsg("200", "请求成功", fileId);
//            //          return ResponseUtil.responseMsg("200", "请求成功");
//        } catch (Exception e) {
//            logger.error(e.getMessage(), e);
//            return ResponseUtil.responseMsg("-80004", "附件上传异常");
//        }
//    }

    /**
     * 上传附件公共方法
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/fileUploadCommon")
    @SecurityParameter(outEncode = false)
    public String fileUploadCommon(@RequestParam("file") MultipartFile[] loadFile, HttpServletRequest request) {
        DataOutput out = DataOutput.success();
        String fileName = loadFile[0].getOriginalFilename();
        if (StringUtils.isBlank(fileName)) {
            return ResponseUtil.responseMsg("-80004", "操作失败,上传文件名为空");
        }
        try {
            SysUserInfo userInfo = UserUtil.getUserInfo(request);
            // 请求中获取AuUser对象
            //SysUserInfo userInfo = (SysUserInfo) request.getSession().getAttribute(Constant.LOGIN_USER);
            if (userInfo == null) {
                return ResponseUtil.responseMsg("-20006", "用户未登录");
            }
            String message = fileFtpUtil.uploadFile(loadFile[0]);
            JSONObject jsonObj = JSONObject.parseObject(message);
            String filePath = jsonObj.getString("filePath");// 获取接口返回的文件id
            String redisKey = RedisUtil.buildKey(":", new String[]{Constant.FILE_PREFIX, filePath});
            RedisUtil.set(redisKey, fileName);
            RedisUtil.expire(redisKey, 24*60*60);
            return ResponseUtil.responseMsg("200", "请求成功", filePath);
           // return ResponseUtil.responseMsg("200", "请求成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResponseUtil.responseMsg("-80004", "附件上传异常");
        }
    }

    /**
     * 上传附件公共方法
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/fileUploadCommonForWeb")
    @SecurityParameter(outEncode = false)
    public String fileUploadCommonForWeb(@RequestParam("file") MultipartFile[] loadFile, HttpServletRequest request) {
        DataOutput out = DataOutput.success();
        String fileName = loadFile[0].getOriginalFilename();
        if (StringUtils.isBlank(fileName)) {
            return ResponseUtil.responseMsg("-80004", "操作失败,上传文件名为空");
        }
        try {
//            SysUserInfo userInfo = UserUtil.getUserInfo(request);
//            // 请求中获取AuUser对象
//            //SysUserInfo userInfo = (SysUserInfo) request.getSession().getAttribute(Constant.LOGIN_USER);
//            if (userInfo == null) {
//                return ResponseUtil.responseMsg("-20006", "用户未登录");
//            }
            String message = fileFtpUtil.uploadFile(loadFile[0]);
            JSONObject jsonObj = JSONObject.parseObject(message);
            String filePath = jsonObj.getString("filePath");// 获取接口返回的文件id
            String redisKey = RedisUtil.buildKey(":", new String[]{Constant.FILE_PREFIX, filePath});
            RedisUtil.set(redisKey, fileName);
            RedisUtil.expire(redisKey, 24*60*60);
            return ResponseUtil.responseMsg("200", "请求成功", filePath);
            // return ResponseUtil.responseMsg("200", "请求成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResponseUtil.responseMsg("-80004", "附件上传异常");
        }
    }



    /**
     * 查询附件信息通用方法
     * */
    @ResponseBody
    @RequestMapping("/selectAllBusinessFile")
    public String selectAllBusinessFile(@RequestBody JSONObject json) {
        String businessType = json.getString("businessType");
        String businessId = json.getString("businessId");
        if(StringUtils.isEmpty(businessType) || StringUtils.isEmpty(businessId)){
            return ResponseUtil.responseMsg("-30000", "缺少必选参数");
        }
        try {
            List<FileInfo> list = fileCommonService.selectAllBusinessFile(businessType, businessId);
            return ResponseUtil.responseMsg("200", "操作成功", list);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResponseUtil.responseMsg("-80005", "附件查询异常");
        }
    }

    /**
     * 删除附件信息通用方法
     * */
    @ResponseBody
    @RequestMapping("/deleteFileByFileId")
    public String deleteFileByFileId(@RequestBody JSONObject json, HttpServletRequest request) {
        // 请求中获取AuUser对象
        SysUserInfo userInfo = (SysUserInfo) request.getSession().getAttribute(Constant.LOGIN_USER);
        if (userInfo == null) {
            return ResponseUtil.responseMsg("-20006", "用户未登录");
        }
        String filePath = json.getString("filePath");
        if(StringUtils.isEmpty(filePath)){
            return ResponseUtil.responseMsg("-30000", "缺少必选参数");
        }
        try{
            fileCommonService.deleteFileByFilePath(json.getString("filePath"), userInfo.getUserInfoNo());
            return ResponseUtil.responseMsg("200", "操作成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResponseUtil.responseMsg("-80006", "附件删除异常");
        }
    }

    /**
     * 文件下载
     *
     * @param json
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/fileDownloadCommon")
    @SecurityParameter
    public String fileDownloadCommon(@RequestBody JSONObject json, HttpServletRequest request, HttpServletResponse response) {
        if( null == json.getString("filePath") || null == json.getString("fileName")){
            return ResponseUtil.responseMsg("-80007", "附件下载参数错误");
        }
        try {
            // 从JSON中取出文件ID
            String filePath = json.getString("filePath");
            String fileName = json.getString("fileName");
            if (StringUtils.isBlank(filePath) || StringUtils.isBlank(filePath)) {
                return ResponseUtil.responseMsg("-30000", "缺少必选参数");
            }
            // 请求中获取AuUser对象
            //SysUserInfo userInfo = (SysUserInfo) request.getSession().getAttribute(Constant.LOGIN_USER);
            SysUserInfo userInfo = UserUtil.getUserInfo(request);
            if (userInfo == null) {
                return ResponseUtil.responseMsg("-20006", "用户未登录");
            }
            InputStream in = fileFtpUtil.downloadFile(filePath);
//            File file = new File(filePath);
//            InputStream in =  new FileInputStream(file);
            byte[] b = new byte[1024];
            int lenth;
            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=\"%s\"", URLDecoder.decode(fileName, "ISO-8859-1")));
            while ((lenth = in.read(b)) > 0) {
                response.getOutputStream().write(b, 0, lenth);
            }
            response.getOutputStream().flush();
            in.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResponseUtil.responseMsg("-80007", "附件下载或查看异常");
        }
        return null;
    }
}
